<template>
  <view class="detail-bottom"
    :class="[getIsIpx ? 'fix-iphonex-button ipx-tabbar-height' : '', getBrandType !== 2 ? 'otherBrands' : '']">
    <view class="bottom-box">

      <view v-for="(item, index) in doneTodosCount" v-if="item.value.is_enable" :key="index" class="item icon-item"
        :class="nowPages.indexOf(item.value.path) != -1 ? 'open' : ''" @click="$preventReClick(clickTab, item)">
        <view class="image-box" v-if="getBrandType !== 2">
          <!-- 异形tabbar -->
          <image v-if="item.value.path == '/litha'"
            :src="nowPages.indexOf(item.value.path) != -1 ? 'https://100000063-1252208446.file.myqcloud.com/images/litha/litha-bottle.png' : 'https://100000063-1252208446.file.myqcloud.com/images/litha/litha-bottle.png'"
            mode="widthFix" class="active_diamond">
          </image>
          <!-- 正常状态 -->
          <image v-else
            :src="nowPages.indexOf(item.value.path) != -1 ? item.value.icon_active_data : item.value.icon_data"
            mode="widthFix" class="tab-svg" :class="[item.value.path.indexOf('live') !== -1 ? 'live-icon' : '']">
          </image>
					<text v-if="getCartNum !== 0 && item.value.path == '/cart'" class="number"
						:style="{ color: nowPages.indexOf(item.value.path) != -1 ? '#1A1A1A' : '#C6C6C6' }">{{ getCartNum<99?getCartNum:'99+' }}</text>
        </view>
        <view class="image-box" v-else>
          <image :src="(nowPages.indexOf(item.value.path) != -1 && item.value.path !== '/cart') || (getCartNum && item.value.path == '/cart')
            ? item.value.icon_active_data
            : item.value.icon_data
            " mode="widthFix" class="tab-svg"></image>
          <text v-if="getCartNum && item.value.path == '/cart'" class="number">{{ getCartNum }}</text>
        </view>
        <view class="doc"
          :style="{ color: nowPages.indexOf(item.value.path) != -1 ? '#1A1A1A' : '#C6C6C6' }">
          {{ item.value.label }}
        </view>
      </view>
    </view>
		<!-- 弱提示 弹窗 -->
		<toast-popup ref="toastPopup" @onToastPopupClick="onToastPopupClick"></toast-popup>
  </view>
</template>

<script>
  import util from '@/utils/util';
  import {
    lithaReport
  } from '@/utils/litha_report';
  import {
    reportEvent,
    EVENT_ID
  } from '@/utils/ab-test.js';
  import {
    getTabInfo
  } from "../../utils/commonFunction"

  export default {
    config: {
      component: true
    },
    props: {
      nowPages: String,
      tsActId: {
        typeof: Number
      },
    },
    components: {},
    data() {
      return {
        tabInfo: [],
        id: 'cms/speicalTip',
        type: '',
        enableLoad: false,
        preQuickClick: true,
        noClick: true,
				showTsTip: true,
				navBarColor: {
					label_color: "#C6C6C6",
					label_color_active: "#1A1A1A"
				},
			}
		},
		computed: {
			doneTodosCount() {
				return this.$store.getters.doneTodosCount;
      },
      getCartNum() {
        return this.$store.state.cartNum;
      },
      getIsIpx() {
        return this.$store.state.isIpx || getApp().globalData.isIpx;
      },
      getBrandType() {
        return this.$store.state.brandType;
      },
      showSalePage() {
        let pages = getCurrentPages();
        var currPage = pages[pages.length - 1];
        if ((currPage.route == 'pages/home/home') && this.$store.state.tsTabbar) {
          return true
        } else {
          return false
        }
      }
    },
    mounted() {
      let pages = getCurrentPages();
      var currPage = pages[pages.length - 1];
      this.nowPage = currPage.route;
    },
    methods: {
			/**
			 * 展示弱提示
			 * @param {Object} msg 文案
			 */
			handleShowTextToast(msg){
				try{
					this.$refs.toastPopup.showToast(msg);
				}catch(e){}
			},
			/**
			 * 若提示按钮点击回调
			 * @param {Object} data.type 类型：confirm确定，cancel取消
			 * @param {Object} data.callBackData 呼气弹窗时传入的数据
			 */
			onToastPopupClick(data){},
      setShowTsTip() {
        this.showTsTip = false
      },
      skipSale() {
        let {
          hideBack,
          listPath,
          landPath,
          tsActId,
          name
        } = uni.getStorageSync('TsInfo')
        let params = {
          "c_pageName": "首页",
          "c_campaignID": tsActId,
          "c_campaignName": name
        }
        getApp().commonClTrack('c_ebmp_home_member_campaign_click_bar', params);
        let storgeText = 'hasVisitTS' + tsActId
        let url = !!uni.getStorageSync(storgeText) ? listPath : landPath
        this.trackClickBar()
        if (hideBack == 'true') {
          uni.redirectTo({
            url: url
          })
        } else {
          uni.navigateTo({
            url: url
          })
        }
        this.trackClickBar()
      },
      trackClickBar() {
        let {
          tsActId,
          name
        } = uni.getStorageSync('TsInfo');
        let params = {
          "c_pageName": "首页",
          "c_campaignID": tsActId,
          "c_campaignName": name
        }
        getApp().commonClTrack('c_ebmp_home_member_campaign_click_bar', params);
      },
      clickTab(item) {
        if (this.preQuickClick) {
          this.tabLink(item)
        } else {
          this.commitTabInfo(item)
        }
      },
      async tabLink(item) {
        let that = this
        // 设置订阅模''
        let {
          activeSubcribeInfo,
          templateIdArr
        } = item.value
        if (item.value.path.indexOf('liveRoom') != -1) {
          let customParams = encodeURIComponent(
            JSON.stringify({
              path: 'pages/index/index',
              pid: 1
            })
          );
          let roomId = item.value.path.substring(item.value.path.indexOf('=') + 1)
          wx.navigateTo({
            url: `plugin-private://wx2b03c6e691cd7370/pages/live-player-plugin?room_id=${roomId}&custom_params=${customParams}`
          });
          return false
        }

        if (item.value.path === '/category') {
          reportEvent(EVENT_ID.CATEGORY.SHANG_CHENG_YE_FANG_WEN);
        }

        if (!!templateIdArr && templateIdArr.length > 0 && this.preQuickClick) {
          let filiterTemplateId = []
          let filiterAtiveSubcribeInfo = []
          activeSubcribeInfo.map(item => {
            let templateId = 'targetSale' + item.activitySubscribeId
            let nowTime = new Date().getTime()
            if ((!!uni.getStorageSync(templateId) && nowTime > uni.getStorageSync(templateId)) || !uni
              .getStorageSync(templateId)) {
              filiterTemplateId.push(item.templateId)
              filiterAtiveSubcribeInfo.push(item)
            }
          })

          if (filiterTemplateId.length > 0) {
            this.requestSubscribe(filiterAtiveSubcribeInfo, filiterTemplateId, item.value.times).then(() => {
              this.tabLinkSkip(item)
            }).catch(() => {
              this.tabLinkSkip(item)
            })
          } else {
            this.tabLinkSkip(item)
          }
        } else {
          this.tabLinkSkip(item)
        }
      },
      tabLinkSkip(item) {
        const path = '/pages' + item.value.path + item.value.path;
        const globalPathConfig = getApp().globalData.pagePath;
        const subPackagePath = globalPathConfig[path];
        if (item.value.path == '/litha') {
          let Params = {
            "campaign": 'SZSH_LITHA_LAUNCH-2023',
            "c_event_category_1": 'browse',
            "c_tab": '邂逅新生',
            "c_link_pagename": '邂逅新生首页',
            'c_link_path': '/page/litha/litha'
          }
          getApp().commonClTrack("c_ebmp_click_tabbar", Params);
          lithaReport("c_ebmp_click_tabbar", Params)
          // 神策埋点
          this.$commonSensors.lithaTrack.tabbarClick({
            "tab_name": "邂逅新生",
            "campaign": 'SZSH_LITHA_LAUNCH-2023'
          })
          uni.setStorageSync('refer_url',this.nowPage);
        } else {
          let trackObj = {
            "/pages/home/home": {
              "c_tab": "首页",
              "c_link_pagename": "首页",
              "c_link_path": "/pages/home/home",
            },
            "/pages/item/categoryNew": {
              "c_tab": "商城",
              "c_link_pagename": "商城",
              "c_link_path": "/pages/item/categoryNew",
            },
            "/pages/litha/litha": {
              "c_tab": "邂逅新生",
              "c_link_pagename": "邂逅新生首页",
              "c_link_path": "/pages/litha/litha",
            },
            "/pages/cart/cart": {
              "c_tab": "购物车",
              "c_link_pagename": "购物车",
              "c_link_path": "/pages/cart/cart",
            },
            "/pages/info/info": {
              "c_tab": "我的",
              "c_link_pagename": "我的",
              "c_link_path": "/pages/info/info",
            }
          }
          getApp().commonClTrack("c_ebmp_click_tabbar", trackObj[path]);
        }
        if (this.nowPages.indexOf(item.value.path) != -1) {
          return;
        } else if (item.value.path == '/favorites') {
          uni.reLaunch({
            url: subPackagePath
          });
        } else if (item.value.path == '/search') {
          uni.reLaunch({
            url: subPackagePath + "?type=category"
          });
        } else if (item.value.path == '/category') {
          uni.reLaunch({
            url: '/pages/item/categoryNew'
          });
        } else {
          uni.reLaunch({
            url: subPackagePath
          });

        }
      },
      requestSubscribe(activeSubcribeInfo, templateIdArr, times) {
        return new Promise(async (reslove, reject) => {
          let that = this;
          let noticeTime = new Date().getTime() + times * 3600000
          this.preQuickClick = false;
          this.noClick = false;
          that.$commonSensors.popupEvent('PopupExposure', {'popup_type' : '订阅消息', 'popup_name': '订阅消息弹窗'})
          that.$commonSensors.modelAuthAsk('活动', templateIdArr)
          uni.requestSubscribeMessage({
            tmplIds: templateIdArr,
            success(res) {
              if (!!res) {
                let result = res
                let keys = Object.keys(result);
                let accept = []
                let reject = []
                for (let i = 0; i < keys.length; i++) {
                  let obj = {}
                  activeSubcribeInfo.map(item => {
                    if (result[keys[i]] == 'accept' && item.templateId == keys[i]) {
                      obj.templateId = keys[i]
                      obj.activitySubscribeId = item.activitySubscribeId
                      accept.push(obj)
                    } else if (result[keys[i]] == 'reject' && item.templateId == keys[i]) {
                      obj.templateId = keys[i]
                      obj.activitySubscribeId = item.activitySubscribeId
                      reject.push(obj)
                    }
                  })
                }

                accept.map(async (item, index) => {
                  let flag;
                  let errorMsg;
                  await util.doSubscribe(item.activitySubscribeId, '', '', 'targetActivity').then(
                    (
                      res) => {
                      if (!!res && res.code == 1000) {
                        let templateId = 'targetSale' + item.activitySubscribeId
                        if (!!uni.getStorageSync(templateId)) {
                          uni.removeStorageSync(templateId)
                        }
                      } else {
                        let templateId = 'targetSale' + item.activitySubscribeId
                        uni.setStorageSync(templateId, noticeTime)
                        errorMsg = res.msg
                        flag = true
                      }
                    })
                  if (accept.length > 0) {
                    if (!!flag) {
                      
                    } else {
                      that.handleShowTextToast('订阅成功')
                    }
                    that.$commonSensors.popupEvent('PopupClick', {'popup_type' : '订阅消息', 'popup_name': '订阅消息弹窗', 'button_name': '允许'})
                  }
                })
                if (reject.length > 0) {
                  reject.map(item => {
                    let templateId = 'targetSale' + item.activitySubscribeId
                    uni.setStorageSync(templateId, noticeTime)
                  })
                  if (reject.length == templateIdArr.length) {

                  }
                  that.$commonSensors.popupEvent('PopupClick', {'popup_type' : '订阅消息', 'popup_name': '订阅消息弹窗', 'button_name': '拒绝'})
                }
              }
              that.commitTabInfo()
            },
            fail(res) {
              activeSubcribeInfo.map(item => {
                let templateId = 'targetSale' + item.activitySubscribeId
                uni.setStorageSync(templateId, noticeTime)
              })
              that.handleShowTextToast('订阅失败')
              that.commitTabInfo()
            },
            complete() {
              reslove();
            }
          });
        })
      },
      commitTabInfo(item) {
        this.preQuickClick = false
        this.noClick = false;
        getTabInfo(this.doneTodosCount).then(() => {
          this.onClick = true
          this.preQuickClick = true
          if (!!item) {
            this.tabLink(item)
          }
        }).catch(() => {
          this.preQuickClick = true
          this.onClick = true
          if (!!item) {
            this.tabLink(item)
          }
        })
      }
    }
  };
</script>
<style lang="less" scoped>
  .ipx-tabbar-height {
    height: 150rpx !important;
  }

  .sale-tip {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    // height: 0;
    // opacity: 0;
    transition: 2s;

    &.sale-tip-up {
      // opacity: .85;
      top: -42px;
    }
  }

  // .sale-tip {
  //   position: absolute;
  //   top: -42px;
  //   left: 0;
  //   right: 0;
  // }

  .detail-bottom {
    // transition: transform;
    // animation: fadeIn .6s linear 1;
    background-color: #444;
    width: 350rpx;
    text-align: center;
    /* border-top: 2rpx solid #ededed; */
  }

  @-webkit-keyframes fadeIn {
    0% {
      opacity: 0;
    }

    100% {
      opacity: 1;
    }
  }

  @keyframes fadeIn {
    0% {
      opacity: 0;
    }

    100% {
      opacity: 1;
    }
  }

  .detail-bottom {
    &.is-special {
      height: 204rpx;
    }
  }

	.detail-bottom {
		font-size: 38rpx;
		width: 100%;
		height: 120rpx;
		position: fixed;
		bottom: 0;
		// background: #000;
		background: #fff;
		z-index: 1000;

		.bottom-box {
			font-size: 38rpx;
			    background-color: #fff;
			    display: flex;
			    /* justify-content: space-around; */
			    /* align-items: flex-start; */
			    box-sizing: border-box;
			    padding: 0 12px;
			    justify-content: space-between;
			    position: relative;

			// font-size: 38rpx;
			// // background-color: #000;
			// background-color: #fff;
			// // height: 120rpx;
			padding-top: 8rpx;
			// // padding-bottom: 10rpx;
			// display: flex;
			// justify-content: space-around;
			// // align-items: center;
			// align-items: flex-start;
			// position: relative;

			// padding-top: 6rpx;
			// .image-box{
			//   .tab-svg{
			//     &:nth-of-type(1){
			//       width:120rpx;
			//     }
			//   }
			// }
		}

    .icon-item {
      display: flex;
      flex-flow: column nowrap;
      justify-content: center;
      align-items: center;
    }

		.item {
			font-size: 38rpx;
			// width: 100%;
			// width: 80rpx;
			// height: 180rpx;
			// bottom: 0;
			// background: #000;
			background: #fff;
			z-index: 10010;
			width: 140rpx;
			height: 88rpx;


			.doc {
				font-size: 20rpx;
				margin-top: 0rpx;
				font-weight: 400;
				// color: #aeaeae !important;
				font-family:'NotoSansSC-Regular'
			}

      .item {
        font-size: 38rpx;
        flex: 1;
        position: relative;
        text-align: center;
        // padding-top: 4rpx;
        display: flex;
        flex-flow: column nowrap;
        align-items: center;
        justify-content: space-between;

				.doc {
					font-size: 20rpx;
					margin-top: 0rpx;
					color: inherit;
					font-weight: 400;
					font-family:'NotoSansSC-Regular'
				}

        .iconfont {
          font-size: 42rpx;
          color: inherit;
        }
      }

			.number {
				display: flex;
				justify-content: center;
				align-items: center;
				position: absolute;
				color: #000;
				// min-width: 32rpx;
				// min-height: 32rpx;
				// line-height: 32rpx;
				padding: 0;
				// border-radius: 50%;
				text-align: center;
				font-size: 24rpx;
				font-family: FrankNew-Regular;
			}
		}

    .open {
      color: #444;

      .doc {
				// color: #fff !important;
      }
    }

    .selec_active {
      .doc {
        color: #ff4856;
      }

      .iconfont {
        color: #ff4856;
        position: relative;
      }
    }

    .tab-svg {
      // width: 100%;
      // width: 80rpx;
    }

    .active {
      border: 1px solid #f23737;
      color: #f23737;
    }
  }

  .fix-iphonex-button {
    bottom: 0 !important;
  }

  .fix-iphonex-button::after {
    content: ' ';
    position: fixed;
    bottom: 0 !important;
    height: auto !important;
    width: 100%;
    background: #fff;
  }

	.image-box {
		position: relative;
		font-size: 0;
		width: 64rpx;
		height: 64rpx;
		// width: 56rpx;
		// height: 56rpx;
		// width: 92rpx;
		// margin: auto;
		// height: 80rpx;
	}

  .detail-bottom.otherBrands {
    // height: 120rpx;

    .image-box {
      position: relative;
      font-size: 0;
      justify-content: center;
      display: flex;
      align-items: center;

      .tab-svg {
        // width: 92rpx;
        // height: 56rpx;
      }
    }

    .item {
      border: none;
    }

		.item .number {
			position: absolute;
			top: 32rpx;
      left: 50%;
			color: #000;
			font-size: 14rpx;
			font-weight: 800;
			z-index: 99999999;
      font-family: FrankNew-Regular;
      width: 27rpx;
      height: 14rpx;
      margin-left: -13.5rpx;
		}
	}

  .live-icon {
    width: 50rpx;
    height: 40rpx !important;
  }

  .icon-item {
    min-width: 80rpx;
  }

  .active_diamond {
    position: absolute;
    width: 43rpx;
    bottom: 10%;
  }
</style>
